<template>
  <div style="position: relative;">
      <!-- canvas 生成海报问题 -->
      <div :id="id" class="code" onselectstart="return false" ref="qrCodeDiv"></div>
      <img class="imgcanvas" :src="drawurl?drawurl:''" style="width:100%;"/>
  </div>
</template>
<script>
// import QRCode from 'qrcodejs2'
export default {
  props: {
    // 背景图
    imgUrl1: {
      type: String,
      default: ''
    },
    // 头像
    imgUrl2: {
      type: String,
      default: ''
    },
    // 二维码
    imgUrl3: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      default: ''
    },
    desc: {
      type: String,
      default: ''
    }
  },
  name: 'canvasPoster',
  data() {
    return {
      id: '',
      drawurl: ''
    }
  },
  created() {
    this.id = 'qrcode' + parseInt(Math.random() * 100)
  },
  mounted() {
    // this.qrcode()
    // this.$nextTick(function() {
    //   this.createPicture()
    // })
    this.drawImg()
  },
  methods: {
    // 画二维码
    // qrcode() {
    //   let _this = this
    //   /* eslint-disable no-new */
    //   new QRCode(this.$refs.qrCodeDiv, {
    //     width: 150,
    //     height: 150,
    //     text: _this.url, // 二维码地址
    //     colorDark: '#000', // 二维码颜色
    //     colorLight: '#fff' // 二维码背景色
    //   })
    // },
    // createPicture() {
    //   let _this = this
    //   document.getElementById(_this.id).lastChild.onload = function () {
    //     _this.imgUrl3 = document.getElementById(_this.id).lastChild.getAttribute('src')
    //     _this.drawImg()
    //   }
    // },
    // 画海报
    drawImg() {
      // 创建高分辨率画布，可自定义放大倍率
      // 473/892.5
      let canvas = this.createHiDPICanvas(473, 892.5, 1)
      let ctx = canvas.getContext('2d')
      this.renderImage(ctx, canvas)
      let _this = this
      /* eslint no-multiple-empty-lines: ["error", { "max": 2, "maxEOF": 0 }] */
      // let time = setTimeout(() => {
      //   _this.convertCanvasToImage(canvas, _this)
      //   clearTimeout(time)
      // }, 500)
    },
    renderImage(ctx, canvas) {
      // 使用Promise加载图片，等图片全部加载完成之后依次绘制
      Promise.all([
        this.loadImage(this.imgUrl1),
        this.loadImage(this.imgUrl2),
        this.loadImage(this.imgUrl3)
      ]).then((imgs) => {
        // canvas导出图片png会默认透明背景，jepg默认黑色背景
        // 这里将背景设置成白色
        // ctx.fillStyle = '#fff'
        ctx.fillRect(0, 0, 473, 892.5)
        ctx.translate(0, 0) // 重新定义起点

        ctx.drawImage(imgs[0], 0, 0, 473, 892.5)
        this.drawAvatar(ctx, imgs[1], 19.8, 805.7, 66.6)
        ctx.drawImage(imgs[2], 353, 789, 100, 100)

        ctx.fillStyle = 'rgba(0, 0, 0, 1)'
        ctx.font = '22px PingFangSC-Regular,PingFang SC'
        if (this.name && this.name.length > 10) {
          this.name = this.name.substr(0, 8) + '...'
        }
        ctx.fillText(this.name, 106, 824.6)

        ctx.fillStyle = 'rgba(0, 0, 0, 1)'
        ctx.font = '14px PingFangSC-Regular,PingFang SC'
        ctx.fillText(this.desc, 106, 864.7)
        this.convertCanvasToImage(canvas, this)
      })
    },
    loadImage(url) {
      return new Promise((resolve) => {
        const img = new Image()
        // 解决图片跨域问题
        img.setAttribute('crossOrigin', 'Anonymous')
        img.src = url + "?v=" + new Date().getTime()
        img.onload = () => resolve(img)
      })
    },
    // 名片头像，圆形
    drawAvatar(ctx, src, x, y, w) {
      const r = w / 2
      ctx.save()
      ctx.arc(x + r, y + r, r, 0, 2 * Math.PI, false)
      ctx.clip()
      ctx.drawImage(src, x, y, w, w)
      ctx.restore()
    },
    convertCanvasToImage(canvas, that) {
      let image = new Image()
      // console.log(JSON.stringify(canvas.toDataURL('image/png')), 'canvas')
      var src = canvas.toDataURL('image/png').replace(/=+$/, '')
      src = src.replace(/[\r\n]/g, '')
      image.src = src
      // console.log(JSON.stringify(src), 'src')
      // this.$nextTick(() => {
      // })
      image.onload = () => {
        that.drawurl = src
      }
      // this.$emit('imgurl', this.drawurl)
    },
    // 创建高分辨率画布
    createHiDPICanvas(w, h, ratio) {
      var PIXEL_RATIO = (function () {
        var c = document.createElement('canvas')
        var ctx = c.getContext('2d')
        var dpr = window.devicePixelRatio || 1
        var bsr = ctx['webkitBackingStorePixelRatio'] || ctx['mozBackingStorePixelRatio'] || ctx['msBackingStorePixelRatio'] || ctx['oBackingStorePixelRatio'] || ctx['backingStorePixelRatio'] || 1
        return dpr / bsr
      })()
      if (!ratio) {
        ratio = PIXEL_RATIO
      }
      const can = document.createElement('canvas')
      can.width = w * ratio
      can.height = h * ratio
      can.style.width = w + 'px'
      can.style.height = h + 'px'
      can.getContext('2d').setTransform(ratio, 0, 0, ratio, 0, 0)
      return can
    }
  }
}
</script>
<style scoped lang="less">
.uniselect{
   -webkit-touch-callout:none;
  -webkit-user-select:none;
  -khtml-user-select:none;
  -moz-user-select:none;
  -ms-user-select:none;
  user-select:none;
}
.code{
  position: absolute;
  left: -1000px;
  top: -1000px;
  opacity: 0;
  width:0;
  height: 0;
  z-index: -1;
}
.imgcanvas{

}
</style>
